package com.grab.dao;

import com.grab.RegionCode;
import com.grab.domain.RegionTable;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author YanShuang
 * @version v_1.0.1
 * @since 2020/9/11 14:46
 */
public class a_gov {

    public static void main(String[] args) {
        try {
            RegionCode regionCode = new RegionCode();
            List<RegionTable> preservation = regionCode.preservation();

            //1、注册JDBC驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2、获取数据库连接
            Connection connection = DriverManager.getConnection(JdbcConstant.DB_URL, JdbcConstant.USER, JdbcConstant.PASS);
            //3、操作数据库
            Statement statement = connection.createStatement();//获取操作数据库的对象

            boolean r = true;
            for (RegionTable regionTable : preservation) {
                if (regionTable.getClassification() == null) {
                    regionTable.setClassification("0");
                }
                String sql = "INSERT INTO china_region_code(`id`, `code`, `name`, `type`, `pid`, `classification`) " +
                        "VALUES (" +
                        "'" + regionTable.getId() + "'" +
                        "," +
                        "'" + regionTable.getCode() + "'" +
                        "," +
                        "'" + regionTable.getName() + "'" +
                        "," +
                        "'" + regionTable.getType() + "'" +
                        "," +
                        "'" + regionTable.getPid() + "'" +
                        "," +
                        "'" + regionTable.getClassification() + "'" +
                        ");";
                int i = statement.executeUpdate(sql);//执行sql，获取结果集
                if (i != 1) {
                    r = false;
                }

            }
            if (r) {
                System.out.println(" 保存成功 ");
            } else {
                System.out.println(" 保存失败 ");
            }

            //4、关闭结果集、数据库操作对象、数据库连接
            statement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
